const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8081 });

const clients = new Map();

server.on('connection', (ws, req) => {
    const userId = req.url.split('/').pop(); // 获取用户ID
    clients.set(userId, ws);
    
    console.log(`用户 ${userId} 已连接`);
    console.log('当前在线用户:', Array.from(clients.keys()));

    ws.on('message', (message) => {
        try {
            const data = JSON.parse(message.toString());
            console.log('收到消息:', data);
            
            if (data.type === 'invitation') {
                console.log(`用户 ${data.from} 邀请 ${data.to} 进行视频通话`);
            } else if (data.type === 'accept') {
                console.log(`用户 ${data.from} 接受了 ${data.to} 的视频通话邀请`);
            } else if (data.type === 'reject') {
                console.log(`用户 ${data.from} 拒绝了 ${data.to} 的视频通话邀请`);
            }

            if (data.to && clients.has(data.to)) {
                console.log(`转发消息给用户 ${data.to}`);
                clients.get(data.to).send(JSON.stringify(data));
            } else {
                console.log(`目标用户 ${data.to} 不在线`);
            }
        } catch (e) {
            if (message.toString() === '心跳') {
                console.log('收到心跳包');
                return;
            }
            console.log('消息解析错误:', e);
        }
    });

    ws.on('close', () => {
        clients.delete(userId);
        console.log(`用户 ${userId} 已断开`);
        console.log('当前在线用户:', Array.from(clients.keys()));
    });
});

console.log('WebSocket 服务器运行在端口 9228');